package com.zhentao.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.User;
import com.zhentao.service.UserService;
import com.zhentao.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 生成验证码
     */
    @RequestMapping("/captcha")
    public Result getCaptcha(HttpServletResponse response) throws IOException {
        // 创建验证码，设置为4位数字验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 0);
        // 生成验证码key
        String captchaKey = UUID.randomUUID().toString();
        // 将验证码存入Redis，设置过期时间5分钟
        redisTemplate.opsForValue().set("captcha:" + captchaKey, lineCaptcha.getCode(), 5);
        
        // 返回验证码图片和key
        Map<String, String> result = new HashMap<>();
        result.put("captchaKey", captchaKey);
        result.put("captchaImage", lineCaptcha.getImageBase64());
        
        return Result.OK(result);
    }

    @RequestMapping("/login")
    public Result login(@RequestBody Map<String, String> loginParams) {
        String userName = loginParams.get("userName");
        String password = loginParams.get("password");
        String captcha = loginParams.get("captcha");
        String captchaKey = loginParams.get("captchaKey");
        // 验证码校验
        // 从Redis获取验证码
        String correctCaptcha = redisTemplate.opsForValue().get("captcha:" + captchaKey);
        // 验证码是否存在
        if (correctCaptcha == null) {
            return Result.ERROR("验证码已过期");
        }
        // 截取后4位并进行不区分大小写的比较
        String validCaptcha = correctCaptcha.substring(correctCaptcha.length()-4);
        if (!validCaptcha.equalsIgnoreCase(captcha)) {
            return Result.ERROR("验证码错误");
        }
        // 删除已使用的验证码
        redisTemplate.delete("captcha:" + captchaKey);

        // 验证用户名密码
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        queryWrapper.eq("password", password);
        User user = userService.getOne(queryWrapper);
        
        return user != null ? Result.OK(user) : Result.ERROR("用户名或密码错误");
    }
}
